package com.spsoft.workflow.common.listener;


import com.google.common.collect.ImmutableSet;
import com.spsoft.workflow.common.enums.BizStatusEnums;
import com.spsoft.workflow.service.ProcessBusinessService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEntityEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEventType;

import org.flowable.engine.delegate.event.AbstractFlowableEngineEventListener;
import org.flowable.engine.delegate.event.FlowableCancelledEvent;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;


/**
 * 监听 {@link ProcessInstance} 的开始与完成，
 *
 */

@Slf4j
@Component
public class BpmProcessInstanceEventListener extends AbstractFlowableEngineEventListener {
    @Resource
    @Lazy
    private ProcessBusinessService businessService;


    public static final Set<FlowableEngineEventType> PROCESS_INSTANCE_EVENTS = ImmutableSet.<FlowableEngineEventType>builder()
                     .add(FlowableEngineEventType.PROCESS_CREATED)
                     .add(FlowableEngineEventType.PROCESS_CANCELLED)
                     .add(FlowableEngineEventType.PROCESS_COMPLETED)
                     .build();

    public BpmProcessInstanceEventListener(){
        super(PROCESS_INSTANCE_EVENTS);
    }

    @Override
    protected void processCreated(FlowableEngineEntityEvent event) {
        log.info("流程创建");
    }

    @Override
    protected void processCancelled(FlowableCancelledEvent event) {
        log.info("流程取消");
    }

    @Override
    protected void processCompleted(FlowableEngineEntityEvent event) {
        log.info("流程实例：{},流程完成",event.getProcessInstanceId());
        //更新业务状态
        businessService.updateBizStatus(event.getProcessInstanceId(), BizStatusEnums.BUSINESS_STATUS_4.getStatus(),"");
    }
}

